//
//  FirCirPictureIDdb.m
//  tcpoctest
//
//  Created by gump on 4/22/13.
//  Copyright (c) 2013 gump. All rights reserved.
//

#import "FirCirPictureIDdb.h"
#import "FirendCircleDataSource.h"
#import "FriendStatus.h"
#import "FirCirNewsDataSource.h"

@implementation FirCirPictureIDdb

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:@"create table if not exists fircirpic(newid text,\
pictureid text)"];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSArray *newidarr = [[DataControl shareControl].fcnewsDS getAllNewsKeys];
    
    for (NSString *strid in newidarr) {
        FriendStatus * fs = [[DataControl shareControl].fcnewsDS getNewsByID:strid];
        
        if (fs != nil) {
            
            [fs.imageIDArray removeAllObjects];
            
            NSString *strsql = [NSString stringWithFormat:@"select pictureid \
from fircirpic where newid = '%@'",strid];
            
            FMResultSet *s = [db executeQuery:strsql];
            while ([s next]) {
                [fs.imageIDArray addObject:[s stringForColumn:@"pictureid"]];
            }
        }
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertPID:(NSString *)newsid withPictureID:(NSString *)pid
{
    if (db == nil)
    {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM fircirpic \
WHERE pictureid = '%@'",pid];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    FMResultSet *s = [db executeQuery:strsql];
    if([s next])
    {
        strsql = [NSString stringWithFormat:@"update fircirpic \
set newid = '%@' \
WHERE pictureid = '%@'"
                  ,newsid
                  ,pid];
    }
    else
    {
        strsql = [NSString stringWithFormat:@"INSERT INTO fircirpic \
(newid,pictureid)\
VALUES ('%@','%@')"
                  ,newsid
                  ,pid];
    }
    
    [db executeUpdate:strsql];
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)delByNewsID:(NSString *)newsid
{
    if (db == nil) {
        return;
    }
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"delete FROM fircirpic WHERE newsid='%@'"
                        ,newsid];
    
    [db executeUpdate:strsql];
    
    [db close];
}

@end
